#pragma once
#include <iostream>
#include <string>
#include <filesystem>
#include "Mutex.hpp"
#include <fstream>
#include <memory>
#include <ctime>
#include <sstream>
#include <cstring>
#include <unistd.h>

namespace LogModel
{
    const std::string path = "./log/";
    const std::string name = "pool.log";

    using namespace MutexModel;
    namespace fs = std::filesystem;
    // 策略接口==多态实现不同的打印方式
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &massage) = 0;
    };

    // 打印在显示器上
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ~ConsoleLogStrategy() {}
        void SyncLog(const std::string &massage) override
        {
            Steward gl(_mutex);
            std::cerr << massage << "\r\n";
        }

    private:
        Mutex _mutex;
    };

    // 打印在log文件里
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string path1 = path, const std::string name1 = name)
            : _path(path1),
              _name(name1)
        {
            Steward gl(_mutex);
            if (fs::exists(_path)) // 判断当前路径是否存在
            {
                // 存在就直接返回
                return;
            }
            // 不存在就创建
            try
            {
                fs::create_directories(_path);
            }
            catch (const fs::filesystem_error &e)
            {
                std::cerr << e.what() << std::endl;
            }
        }

        void SyncLog(const std::string &massage) override
        {
            std::string log = _path + _name;
            std::ofstream out(log.c_str(), std::ios::app); // 追加方式
            if (!out.is_open())
                return;
            out << massage << "\n";
            out.close();
        }

        ~FileLogStrategy()
        {
        }

    private:
        std::string _path;
        std::string _name;
        Mutex _mutex;
    };

    // 日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string GetTimeLog()
    {
        time_t timestamp = time(nullptr);
        tm *local_time = localtime(&timestamp);

        std::stringstream logmassage;
        logmassage << local_time->tm_year + 1900 << "-"
                   << local_time->tm_mon + 1 << "-" << local_time->tm_mday
                   << " " << local_time->tm_hour << ":" << local_time->tm_min << ":" << local_time->tm_sec;
        return logmassage.str();
    }

    std::string GetType(LogLevel type)
    {
        switch (type)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        default:
            return "UNKNOW";
        }
    }

    class Logger
    {
    public:
        Logger()
        {
            UseConsoleStrategy(); // 默认使用显示器打印
        }
        // 显示器
        void UseConsoleStrategy()
        {
            _strategy = std::make_unique<ConsoleLogStrategy>();
        }
        // 文件
        void UseFileStrategy()
        {
            _strategy = std::make_unique<FileLogStrategy>();
        }
        ~Logger()
        {
        }
        // 实现一个内部类来将日志信息的内容整合,使用RAII的风格
        class LogMassage
        {
        private:
            LogLevel _type;         // ⽇志等级
            std::string _curr_time; // ⽇志时间
            pid_t _pid;             // 进程pid
            std::string _filename;  // 对应的⽂件名
            int _line;              // 对应的⽂件⾏号
            Logger &_logger;        // 引用外部logger类, 方便使用策略进行刷新
            std::string _loginfo;   // ⼀条合并完成的，完整的日志信息
        public:
            LogMassage(LogLevel type, std::string filename, int line, Logger &logger)
                : _type(type),
                  _curr_time(GetTimeLog()),
                  _pid(getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                // 获取[ERROR][time][pid][name][line]-
                std::stringstream logmassage;
                logmassage << "[" << GetType(_type) << "]"
                           << "[" << _curr_time << "]"
                           << "[" << _pid << "]"
                           << "[" << _filename << "]"
                           << "[" << _line << "]-";
                _loginfo = logmassage.str();
            }

            template <class T>
            LogMassage& operator<<(const T &info)
            {
                std::stringstream log;
                log << info;
                _loginfo += log.str();
                return *this; // 返回当前对象，方便持续<<
            }

            ~LogMassage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }
        };
        LogMassage operator()(LogLevel type, std::string filename, int line)
        {
            return LogMassage(type, filename, line, *this);
        }

    private:
        std::unique_ptr<LogStrategy> _strategy;
    };

    Logger logger;
    // 使⽤宏，可以进⾏代码插⼊，⽅便随时获取⽂件名和⾏号

#define LOG(type) logger(type, __FILE__, __LINE__)
    // 提供选择使⽤何种⽇志策略的⽅法
#define ENABLE_CONSOLE_LOG_STRATEGY() logger.UseConsoleStrategy()
#define ENABLE_FILE_LOG_STRATEGY() logger.UseFileStrategy()
}
